package com.atguigu.springcloud.alibaba.controller;

import java.net.URI;
import java.util.concurrent.ThreadLocalRandom;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @auther zzyy
 * @create 2020-02-10 12:02
 */
@RestController
@Slf4j
public class OrderNacosController
{
    @Resource
    private RestTemplate restTemplate;

    @Value("${service-url.nacos-user-service}")
    private String serverURL;

    @Resource
    private DiscoveryClient discoveryClient;
    @Resource
    private LoadBalanced loadBalanced; //org.springframework.cloud.client.loadbalancer
    @Resource
    private LoadBalancerClient loadBalancerClient; //org.springframework.cloud.client.loadbalancer

    @GetMapping("/consumer/payment/lb")
    public String getPaymentLB()
    {
        ServiceInstance serviceInstance = loadBalancerClient.choose("你自己的微服务名称");
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri+"/payment/lb",String.class);
    }



    @GetMapping("/consumer/payment/nacos/{id}")
    public String paymentInfo(@PathVariable("id") Long id)
    {
        return restTemplate.getForObject(serverURL+"/payment/nacos/"+id,String.class);
    }

    @GetMapping("/consumer/payment/nacos/discovery")
    public String discovery()
    {
        String result = restTemplate.getForObject(serverURL+"/payment/nacos/discovery", String.class);

        return result;
    }

    @GetMapping("/consumer/payment/nacos/discovery2")
    public String discovery2()
    {
        // 获取请求示例
        List<ServiceInstance> instances = discoveryClient.getInstances("nacos-payment-provider");

        for (ServiceInstance ele : instances) {
            System.out.println(ele.getServiceId());
            System.out.println(ele.getInstanceId());
            System.out.println(ele.getPort());
            System.out.println(ele.getUri());
        }


        List<String> collect = instances.stream()
                .map(instance -> "http://"+instance.getServiceId() + "/payment/nacos/discovery")
                .collect(Collectors.toList());

        // 随机算法
        int i = ThreadLocalRandom.current().nextInt(collect.size());
        String targetURL =  collect.get(i);

        log.info("******请求的目标地址： {}", targetURL);


        String result = restTemplate.getForObject(targetURL, String.class);

        return result;
    }


}
